<template>
  <Row>
    <Col span="24">
    <Form :model="formData" :label-width="100" :rules="rules" ref="refRorm">
      <FormItem label="原密码：" prop="oldPwd">
        <Input v-model.trim="formData.oldPwd" type="password" placeholder="请输入密码..." clearable />
      </FormItem>
      <FormItem label="确认密码：" prop="newPwd">
        <Input v-model.trim="formData.newPwd" type="password" placeholder="确认密码..." clearable />
      </FormItem>
      <FormItem label="确认新密码：" prop="newPwd1">
        <Input v-model.trim="formData.newPwd1" type="password" placeholder="确认密码..." clearable />
      </FormItem>
    </Form>
    </Col>
    <Col span="24" style="text-align:right; border-top:1px solid #e8eaec;padding-top:15px;">
    <Button @click="onCancel">取消</Button>
    <Button @click="onSubmit" type="primary">提交</Button>
    </Col>
  </Row>
</template>

<script>
import { chagePwd } from "@/api";
const passWordPattern = /^[a-zA-Z0-9_-]{2,16}$/;
export default {
  props: {
    userId: {
      type: String,
      default: ""
    }
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请在输入密码"));
      } else if (value === this.formData.oldPwd) {
        callback(new Error("新密码不能和原密码相同"));
      } else {
        if (value.length >= 6) {
          if (!passWordPattern.test(value)) {
            callback(new Error("密码只能输入字母、数字、英文特殊字符"));
          } else {
            callback();
          }
        } else {
          callback(new Error("密码至少输入6个字符"));
        }
      }
    };
    const validatePassCheck = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请在输入一遍密码"));
      } else if (value !== this.formData.newPwd) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      formData: {
        oldPwd: null,
        newPwd: null,
        newPwd1: null
      },
      rules: {
        oldPwd: [
          {
            required: true,
            trigger: "blur",
            message: "请输入原密码"
          }
        ],
        newPwd: [
          {
            required: true,
            trigger: "blur",
            validator: validatePass
          }
        ],
        newPwd1: [
          {
            required: true,
            trigger: "blur",
            validator: validatePassCheck
          }
        ]
      }
    };
  },
  methods: {
    onSubmit() {
      this.$refs.refRorm.validate(valid => {
        if (valid) {
          const params = {
            userId: this.userId,
            oldPwd: this.formData.oldPwd,
            newPwd: this.formData.newPwd
          };
          chagePwd(params).then(res => {
            if (res.code === 200) {
              this.$Message.success("操作成功");
              this.$emit("save");
            } else {
              this.$Message.error(res.message);
            }
          });
        }
      });
    },
    onCancel() {
      this.$emit("off");
    }
  }
};
</script>
